package com.crl.module.pool
{
	import com.crl.core.ClassFactory;
	
	import flash.utils.Dictionary;
	
	
	/**
	 * 
	 * @author crl
	 * 
	 */	
	public class ObjectPoolCache
	{
		
		protected static const DEFAULT_POOL_SIZE:int = 5;
		
		private static var _instance : ObjectPoolCache;
		public static function getInstance():ObjectPoolCache
		{
			if (_instance == null) {
				_instance = new ObjectPoolCache();
			}
			return _instance;
		}
		
		protected var _pools:Dictionary;
		
		
		public function ObjectPoolCache() 
		{
			if(_instance){
				throw new Error("不能创建此对像,此为单件类");
			}
			_pools = new Dictionary();
		}
	
		public function get pools():Dictionary { 
			return _pools; 
		}
		
		
		public function get(objectClass:Class):*
		{
			var pool:ObjectPool =  this.getPool(objectClass);
			var obj:* = pool.get();
			
			return obj
		}
		
	
		public function set(object:*):void
		{
			var objectClass:Class = object.constructor as Class;
			var pool:ObjectPool =  this.getPool(objectClass);
			pool.set(object);
		}
		
		
		public function initPool(objectClass:Class, minSize:uint = 0 ):void
		{
			if (_pools[objectClass] == null)
			{
				minSize = (minSize > 0) ? minSize : DEFAULT_POOL_SIZE;
				var facotry:ClassFactory=new ClassFactory(objectClass);
				var pool:ObjectPool = new ObjectPool(facotry, minSize);
				this.addPool(pool);
			}
		}
		
		
		/**
		 * 添加一个对像池; 
		 * @param pool
		 * 
		 */		
		public function addPool(pool:ObjectPool):void
		{
			if (_pools[pool.factory.generator] != null)
			{
				throw new Error("Pool for "+pool.factory.generator+" already exists");
			}else {
				_pools[pool.factory.generator] = pool;
			}
		}
		
		
		/**
		 * 取得一个对像池; 
		 * @param objectClass
		 * @return 
		 * 
		 */		
		public function getPool(objectClass:Class):ObjectPool
		{
			if (_pools[objectClass] == null)
			{
				initPool(objectClass);
			}
			
			return _pools[objectClass] as ObjectPool;
		}
		
		
		/**
		 *  让一个对像池填满;
		 * @param objectClass
		 * 
		 */		
		protected function populatePool(objectClass:Class):void
		{
			var pool:ObjectPool = _pools[objectClass];
			pool.populate();
		}
	}

}